import os
import sys

import xlrd

from . import settings
from .settings import rootPath, ReportTemplate, ReportTemplatex

sys.path.append(rootPath)

from .hrunTestCase import HrunTestCase
from .core.HrunCall import HrunCall

configKeys = []
testcaseKeys = ["name", "request"]


KEY_ALL = 'All'
# testsuite模式， sheet名称
KEY_TESTSUITE = 'TestSuite'
# SheetSuite模式  sheet名称
KEY_SHEETSUITE = 'SheetSuite'


class ExcelCall:
    def __init__(self, workdir='') -> None:
        super().__init__()

        self.excelObj = None
        self.workDir = settings.set_WorkDir(workdir)

        self.baseDir = rootPath
        self.excelFile = ""
        self.tcname = ''

        # Hruncall 核心对象
        self.hrun = HrunCall()

        # hrun 测试用例 对象
        self.hruntc = HrunTestCase()

    def loadExcel(self):
        # 读取excel
        # if type == 'r':
        # 打开文件
        self.workbook = xlrd.open_workbook(self.excelFile)
        self.sheet_names = self.workbook.sheet_names()

    def _excelToObj(self, outjsonfile=''):
        """
        读取excel 并转化为testcase对象
        :param excelfilename:
        :param sheetname:
        :param outjsonfile:
        :return:
        """

        self.hrun.testcaseObj = self.loadAllSheets()

        if outjsonfile != "":
            self.hruntc.toJsonFile(os.path.join(self.workDir, outjsonfile))

    def _sheetToObj(self, sheetname='', outjsonfile=''):
        """
        读取excel sheet并转化为testcase对象
        :param excelfilename:
        :param sheetname:
        :param outjsonfile:
        :return:
        """
        obj_testcase = self.loadSheet2List(sheetname)
        self.hrun.testcaseObj = obj_testcase

        if outjsonfile != "":
            self.hruntc.toJsonFile(os.path.join(self.workDir, outjsonfile))

        return obj_testcase

    def CallHrunExcel(self, excelfilename, sheetType='', outjsonfile='', log_level='INFO', isExtendReport=False,
                      reportURL=''):
        settings.report_url = reportURL
        settings.extend_report_type = isExtendReport
        settings.log_level = log_level

        print( \
            """Work space = %s
            Report dir = %s   """ % (self.workDir, os.path.join(self.workDir, 'reports\\')))

        self.excelFile = excelfilename
        self.loadExcel()

        # if KEY_TESTSUITE in self.sheet_names:
        if sheetType == KEY_TESTSUITE and KEY_TESTSUITE in self.sheet_names:
            # 执行Excel Testsuite模式
            self.hrun.testcaseObj = self.loadTSuite()

            # print(json.dumps(self.hrun.testcaseObj , indent=4, separators=(',', ':'), ensure_ascii=False))
        elif sheetType == KEY_SHEETSUITE and KEY_SHEETSUITE in self.sheet_names:
            self.hrun.testcaseObj = self.loadTSuiteSheet()

        elif sheetType != "" and sheetType not in [KEY_TESTSUITE, KEY_ALL, KEY_SHEETSUITE]:
            if sheetType not in self.sheet_names:
                # 如果sheetname 不存在，则取其中的第一个sheet
                sheetType = self.sheet_names[0]

            # print(sheetname)
            self._sheetToObj(sheetType, outjsonfile)

        elif sheetType == KEY_ALL:
            # 执行所有的 sheet
            self._excelToObj(outjsonfile)
            # print(json.dumps(self.hrun.testcaseObj, indent=4, separators=(',', ':'), ensure_ascii=False))

        else:
            raise Exception("不支持的SheetType：" + sheetType)

        self.hrun.callHrun(tcname=self.tcname)

    def loadTSuite(self):
        # Hrun自带的testsuite 模式
        oTestSuit = self.hruntc.fromSheet2tSuite(self.workbook.sheet_by_name(KEY_TESTSUITE), self.workbook)
        self.tcname = oTestSuit[0]['config']['name']

        return oTestSuit

    def loadTSuiteSheet(self):
        # 封装的Sheetsuite 模式

        oTestSuit = self.hruntc.fromSheet2sheetSuite(self.workbook.sheet_by_name(KEY_SHEETSUITE), self.workbook)

        self.tcname = oTestSuit[0]['config']['name']

        return oTestSuit

    def loadAllSheets(self):
        self.sheets = []
        # 循环编辑
        for sheet_name in self.sheet_names:
            if sheet_name in [KEY_SHEETSUITE, KEY_TESTSUITE]:
                # 剔除掉 suite页面
                continue

            self.sheets.append(self.loadSheet2List(sheet_name)[0])

        # 将得到的excel数据返回进行处理
        return self.sheets

    def loadSheet2List(self, sheet_name):
        # 通过每个sheetname获取到每个页的内容
        sheet = self.workbook.sheet_by_name(sheet_name)

        return self.hruntc.fromSheet2List(sheet)




def callexcel():
    excelfile = "demo_httprunner.xls"
    excelfile = "F:\\zsah_work\\shoubahrun\\testcases\\shoubalogin.xls"
    excelfile = "E:\\zsah-git\\zsah_py_tester\\hrunEX\\workdir\\excel\\runsheets.xls"
    outfile = "exceldemo.json"

    sheetname = 'demo-testcase-get-token'  # 'testerhome-login'
    sheetname = 'sheet1'

    xlsCaller = ExcelCall()
    # xlsCaller.CallHrunExcel(excelfile, sheetname, outfile)
    xlsCaller.CallHrunExcel(excelfile, '', '')


if __name__ == "__main__":
    callexcel()
